/**
 * 智能补齐所有题型到50题 - 支持各种文件格式
 * 运行：node math-academy/scripts/智能补齐所有题型.js
 */

const fs = require('fs');
const path = require('path');

const ROOT = path.join(__dirname, '..', '..');
const QUESTIONS_DIR = path.join(ROOT, 'questions');
const PRIMARY_DIR = path.join(QUESTIONS_DIR, 'primary-school');
const MIDDLE_DIR = path.join(QUESTIONS_DIR, 'middle-school');

function read(file) { return fs.readFileSync(file, 'utf-8'); }
function write(file, content) { fs.writeFileSync(file, content, 'utf-8'); }
function s(str){ return JSON.stringify(String(str)).slice(1,-1); }

// 统计题目数量
function countQuestions(content) {
  const matches = content.match(/\{\s*stem:/g);
  return matches ? matches.length : 0;
}

// 生成题目（根据题型智能生成）
function generateQuestions(topic, startIndex, count) {
  const questions = [];
  
  for (let i = 0; i < count; i++) {
    const index = startIndex + i;
    const difficulty = i < count * 0.2 ? 1 : 
                      i < count * 0.5 ? 2 : 
                      i < count * 0.8 ? 3 : 
                      i < count * 0.95 ? 4 : 5;
    
    let stem, answer, solution;
    
    // 根据题型生成具体题目
    if (topic.includes('体积计算')) {
      const l = 5 + index, w = 4 + index, h = 3 + index;
      stem = `一个长方体的长是${l}厘米，宽是${w}厘米，高是${h}厘米，求体积。`;
      answer = [l * w * h];
      solution = `体积 = 长 × 宽 × 高 = ${l} × ${w} × ${h} = ${l*w*h}立方厘米`;
    } else if (topic.includes('面积计算')) {
      const r = 5 + index;
      stem = `一个圆的半径是${r}厘米，求面积。（π取3.14）`;
      answer = [Math.round(3.14 * r * r * 100) / 100];
      solution = `面积 = πr² = 3.14 × ${r}² = ${answer[0]}平方厘米`;
    } else if (topic.includes('空间想象')) {
      const a = 5 + index;
      stem = `一个正方体的棱长是${a}厘米，求表面积。`;
      answer = [6 * a * a];
      solution = `表面积 = 6 × 棱长² = 6 × ${a}² = ${answer[0]}平方厘米`;
    } else if (topic.includes('排列组合')) {
      const n = 6 + index, r = 3;
      stem = `从${n}个不同的元素中选${r}个进行排列，有多少种方法？`;
      const result = n * (n-1) * (n-2);
      answer = [result];
      solution = `A(${n},${r}) = ${n} × ${n-1} × ${n-2} = ${result}`;
    } else if (topic.includes('日历问题')) {
      const day = 1 + (index % 7);
      const days = ['一', '二', '三', '四', '五', '六', '日'];
      stem = `某月1号是星期${days[day-1]}，这个月的15号是星期几？`;
      const ans = (day + 14 - 1) % 7 + 1;
      answer = [`星期${days[ans-1]}`];
      solution = `从1号到15号经过14天，14÷7=2周，所以15号也是星期${days[ans-1]}`;
    } else if (topic.includes('图形计数')) {
      const n = 3 + index;
      stem = `一个${n}×${n}的方格，有多少个小正方形？`;
      answer = [n * n];
      solution = `${n}×${n}的方格有${n*n}个小正方形`;
    } else if (topic.includes('抽屉原理')) {
      const apples = 10 + index, drawers = 3 + (index % 4);
      stem = `有${apples}个苹果放入${drawers}个抽屉，至少有一个抽屉放了多少个苹果？`;
      answer = [Math.ceil(apples / drawers)];
      solution = `根据抽屉原理，至少有一个抽屉放了⌈${apples}÷${drawers}⌉=${answer[0]}个苹果`;
    } else if (topic.includes('数字谜题')) {
      const a = 3 + (index % 7), b = 5 + (index % 5);
      stem = `一个两位数，十位数字是${a}，个位数字是${b}，这个数是多少？`;
      answer = [a * 10 + b];
      solution = `这个两位数是${a}${b}，即${answer[0]}`;
    } else if (topic.includes('一元一次方程')) {
      const a = 2 + index, b = 5 + index, c = 15 + index * 2;
      stem = `解方程：${a}x + ${b} = ${c}`;
      answer = [(c - b) / a];
      solution = `${a}x = ${c} - ${b} = ${c-b}\nx = ${c-b} ÷ ${a} = ${answer[0]}`;
    } else if (topic.includes('二元一次方程组')) {
      const s = 10 + index, d = 2 + index;
      stem = `解方程组：x + y = ${s}，x - y = ${d}`;
      const x = (s + d) / 2, y = (s - d) / 2;
      answer = [x, y];
      solution = `x = (${s} + ${d}) ÷ 2 = ${x}\ny = (${s} - ${d}) ÷ 2 = ${y}`;
    } else if (topic.includes('不等式')) {
      const a = 2 + index, b = 3 + index, c = 10 + index * 2;
      stem = `解不等式：${a}x + ${b} > ${c}`;
      answer = [`x > ${(c - b) / a}`];
      solution = `${a}x > ${c} - ${b} = ${c-b}\nx > ${c-b} ÷ ${a} = ${(c-b)/a}`;
    } else if (topic.includes('函数基础')) {
      const a = 2 + index, b = 3 + index, x = 5 + index;
      stem = `已知函数y = ${a}x + ${b}，当x = ${x}时，求y的值。`;
      answer = [a * x + b];
      solution = `y = ${a} × ${x} + ${b} = ${answer[0]}`;
    } else if (topic.includes('回归分析')) {
      const a = 2 + index, b = 3 + index, x = 5 + index;
      stem = `一组数据的回归方程是y = ${a}x + ${b}，当x = ${x}时，预测y的值。`;
      answer = [a * x + b];
      solution = `y = ${a} × ${x} + ${b} = ${answer[0]}`;
    } else if (topic.includes('实际应用')) {
      const days = 10 + index, total = (10 + index) * (100 + index * 10), extra = 10 + index;
      stem = `某工厂计划${days}天生产${total}个零件，实际每天多生产${extra}个，实际用了多少天？`;
      const daily = total / days;
      const actualDays = Math.round(total / (daily + extra) * 10) / 10;
      answer = [actualDays];
      solution = `计划每天生产${daily}个，实际每天生产${daily + extra}个\n实际用时${total} ÷ ${daily + extra} ≈ ${actualDays}天`;
    } else if (topic.includes('数学建模')) {
      const base = 100 + index * 10, rate = 2 + (index % 3), years = 5 + index;
      stem = `某城市人口每年增长${rate}%，现有人口${base}万，${years}年后人口约多少万？`;
      const result = Math.round(base * Math.pow(1 + rate/100, years) * 10) / 10;
      answer = [result];
      solution = `${years}年后人口 = ${base} × (1 + ${rate}%)^${years} ≈ ${result}万`;
    } else if (topic.includes('竞赛基础')) {
      const n = 10 + index * 2;
      stem = `求${n}的所有因数之和。`;
      let sum = 0;
      for (let j = 1; j <= n; j++) {
        if (n % j === 0) sum += j;
      }
      answer = [sum];
      solution = `${n}的因数有：${Array.from({length: n}, (_, i) => i + 1).filter(j => n % j === 0).join(', ')}\n因数之和 = ${sum}`;
    } else if (topic.includes('综合压轴题')) {
      const a = 2 + index, b = 3 + index, c = 4 + index;
      stem = `已知函数y = ${a}x² + ${b}x + ${c}，求顶点坐标。`;
      const x = -b / (2 * a);
      const y = a * x * x + b * x + c;
      answer = [[Math.round(x * 100) / 100, Math.round(y * 100) / 100]];
      solution = `顶点横坐标 x = -b/(2a) = -${b}/(2×${a}) = ${x}\n顶点纵坐标 y = ${Math.round(y * 100) / 100}\n顶点坐标(${x}, ${Math.round(y * 100) / 100})`;
    } else {
      // 默认模板
      stem = `${topic}练习题${index + 1}：请根据题型特点完成此题。`;
      answer = [0];
      solution = "【待完善】此题目为自动生成，解析待补充。";
    }
    
    questions.push({
      stem,
      difficulty,
      answer,
      hint1: "分析题目条件",
      hint2: "列出计算步骤",
      solution
    });
  }
  
  return questions;
}

// 智能补齐文件
function smartFill(filePath) {
  const topic = path.basename(filePath, '.ts');
  const content = read(filePath);
  const currentCount = countQuestions(content);
  
  if (currentCount >= 50) {
    console.log(`✅ ${topic}: 已有${currentCount}题，无需补充`);
    return { topic, before: currentCount, after: currentCount, added: 0 };
  }
  
  const needed = 50 - currentCount;
  console.log(`🔄 ${topic}: 当前${currentCount}题，需补充${needed}题...`);
  
  // 生成新题目
  const newQuestions = generateQuestions(topic, currentCount, needed);
  
  // 构建新题目字符串
  const newQuestionsStr = newQuestions.map(q => {
    const ansStr = Array.isArray(q.answer) ? 
      `[${q.answer.map(a => typeof a === 'number' ? a : `"${s(a)}"`).join(', ')}]` :
      `[${typeof q.answer === 'number' ? q.answer : `"${s(q.answer)}"`}]`;
    return `  { stem: "${s(q.stem)}", difficulty: ${q.difficulty}, answer: ${ansStr}, hint1: "${s(q.hint1)}", hint2: "${s(q.hint2)}", solution: "${s(q.solution)}" }`;
  }).join(',\n');
  
  // 找到最后一个题目的位置，在其后添加
  const lastQuestionMatch = content.lastIndexOf('{ stem:');
  if (lastQuestionMatch === -1) {
    console.log(`❌ ${topic}: 无法找到题目位置`);
    return { topic, before: currentCount, after: currentCount, added: 0, error: true };
  }
  
  // 找到最后一个题目的结束位置
  let pos = lastQuestionMatch;
  let braceCount = 0;
  let inString = false;
  let escapeNext = false;
  
  for (let i = pos; i < content.length; i++) {
    const char = content[i];
    
    if (escapeNext) {
      escapeNext = false;
      continue;
    }
    
    if (char === '\\') {
      escapeNext = true;
      continue;
    }
    
    if (char === '"' && !escapeNext) {
      inString = !inString;
      continue;
    }
    
    if (!inString) {
      if (char === '{') braceCount++;
      if (char === '}') {
        braceCount--;
        if (braceCount === 0) {
          pos = i + 1;
          break;
        }
      }
    }
  }
  
  // 在找到的位置后插入新题目
  const before = content.substring(0, pos);
  const after = content.substring(pos);
  
  const newContent = before + ',\n' + newQuestionsStr + after;
  
  write(filePath, newContent);
  
  console.log(`✅ ${topic}: 补充完成，现有50题`);
  return { topic, before: currentCount, after: 50, added: needed };
}

function main() {
  console.log('🚀 开始智能补齐所有题型到50题...\n');
  
  const results = [];
  
  // 处理小学题库
  console.log('📚 处理小学题库...');
  const primaryFiles = fs.readdirSync(PRIMARY_DIR).filter(f => f.endsWith('.ts')).sort();
  for (const file of primaryFiles) {
    const result = smartFill(path.join(PRIMARY_DIR, file));
    results.push(result);
  }
  
  // 处理初中题库
  console.log('\n📚 处理初中题库...');
  const middleFiles = fs.readdirSync(MIDDLE_DIR).filter(f => f.endsWith('.ts')).sort();
  for (const file of middleFiles) {
    const result = smartFill(path.join(MIDDLE_DIR, file));
    results.push(result);
  }
  
  // 统计
  console.log('\n📊 补齐统计：');
  console.log('='.repeat(60));
  const totalAdded = results.reduce((sum, r) => sum + r.added, 0);
  const totalFiles = results.length;
  const modifiedFiles = results.filter(r => r.added > 0).length;
  const errorFiles = results.filter(r => r.error).length;
  
  console.log(`总题型数: ${totalFiles}个`);
  console.log(`已修改题型: ${modifiedFiles}个`);
  console.log(`失败题型: ${errorFiles}个`);
  console.log(`新增题目: ${totalAdded}题`);
  console.log(`预计总题目数: ${totalFiles * 50}题`);
  console.log('='.repeat(60));
  
  // 保存报告
  const reportPath = path.join(ROOT, 'math-academy', 'docs', '智能补齐报告.json');
  write(reportPath, JSON.stringify(results, null, 2));
  console.log(`\n📄 详细报告已保存到: ${reportPath}`);
  
  console.log('\n✅ 补齐完成！');
}

main();

